import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入一级路由
import Layout from '@/views/layout'
import Login from '@/views/login'
import NotFound from '@/views/404'
// 导入二级路由
import Home from '@/views/layout/home'
import Qa from '@/views/layout/qa'
import User from '@/views/layout/user'
import Vide from '@/views/layout/video'

import store from '@/store/index'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    // 重定向
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home
      },
      {
        path: 'qa',
        component: Qa
      },
      {
        path: 'vide',
        component: Vide
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

const loginURL = ['/user']
router.beforeEach((to, from, next) => {
  const token = store.state.user.token.token
  if (token) {
    next()
  } else {
    // 没有token
    if (loginURL.some((item) => to.path === item)) {
      // if成立，需要登录
      // next('/login')
      router.push('/login')
    } else {
      next()
    }
  }
})

export default router
